import Vue from 'vue'
import Vuex from 'vuex'
import { INC, DEC } from "../mutations/index"

Vue.use(Vuex)

import msbd from "./msbd"
import shop from "./shop"
import car from "./car"

const STORAGE_KEY = 'todoMvc'

export default new Vuex.Store({
  state: {
    count: 0,

    todos: JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'),
    buytext: "提交",
  },

  mutations: {
    [INC](state, nub) {
      state.count += nub
    },
    [DEC](state, nub) {
      state.count -= nub
    },
    add(state, num) {
      state.count += num
    },
    littles(state, num) {
      state.count -= num;
    },
    // 
    addTodo(state, todo) {
      state.todos.push(todo)
    },
    removeTodo(state, todo) {
      state.todos.splice(state.todos.indexOf(todo), 1)
    },
    editTodo(state, { todo, text = todo.text, done = todo.done }) {
      let index = state.todos.indexOf(todo)
      state.todos.splice(index, 1, {
        ...todo,
        text,
        done
      })
    },
  },

  actions: {
    asyncInc({ commit }, nub) {
      commit(INC, nub)
    },
    asyncDec({ context }, nub) {
      context.commit(DEC, nub)
    },
    asyncAdd(context, num) {
      context.commit('add', num.num)
    },
    asyncLittle({ commit, dispatch }, num) {
      // console.log(num);
      // console.log(commit)
      // console.log(dispatch)
      commit('littles', num);
      // dispatch('text');   
    },

    // todo
    addTodo({ commit, getters }, text) {
      commit('addTodo', {
        text,
        done: false
      })
      console.log(getters)
    },
    // 删除
    removeTodo({ commit }, todo) {
      commit('removeTodo', todo)
    },
    // 状态 完成 / 未完成
    toggleTodo({ commit }, todo) {
      commit('editTodo', { todo, done: !todo.done })
    },
    // 修改
    editTodo({ commit }, { todo, value }) {
      commit('editTodo', { todo, text: value })
    },
    // 全选
    toggleAll({ state, commit }, done) {
      state.todos.forEach((todo) => {
        commit('editTodo', { todo, done })
      })
    },
    // 删除所有已完成
    clearCompleted({ state, commit }) {
      state.todos.filter(todo => todo.done)
        .forEach(todo => {
          commit('removeTodo', todo)
        })
    },
  },

  getters: {},

  modules: {
    msbd,
    shop,
    car
  }
})
